package sax.utils;

import java.util.List;

import sax.representation.Image;
import sax.representation.PAA;
import sax.representation.SAX;
import sax.representation.TimeSeries;

/**
 * Class which creates SAX representation from image
 * 
 * @author Krzysztof Figaj
 *
 */
public class SAXCreator {

	public static SAX create(String imageName){
		
		Image newImage = ImageMenager.loadImage(imageName);
		
		TimeSeriesCreator timeSeriesCreator = new TimeSeriesCreator();
		TimeSeries timeSeries = timeSeriesCreator.create(newImage);
		
//		ImageMenager.saveImage(imageToSave, formatName, filePath);
		
		TimeSeries normalizedTimeSeries = TimeSeries.normalize(timeSeries);
		TimeSeries reductedTimeSeries = TimeSeries.reduce(normalizedTimeSeries,
				Settings.TIME_SERIES_NUMBER);
		
		PAA paa = PAACreator.create(reductedTimeSeries,
				Settings.PAA_ELEMENTS_NUMBER);
		
		SAX sax = discretization(paa, Settings.ALPHABET_NUMBER);
		if(sax != null){
			sax.setImageName(imageName);
			sax.setAlphabetCount(Settings.ALPHABET_NUMBER);
		}
		
		return sax;
	}
	
	private static SAX discretization(PAA paa, int numberOfLetters){
		SAX sax = new SAX();
		String result = "";
		if(Settings.breakpoints.containsKey(numberOfLetters)){
			List<Double> breakPoints = Settings.breakpoints.get(numberOfLetters);
			double[] paaElements = paa.getElements();
			for(double element: paaElements){
				result += getLetter(breakPoints, element);
			}
			sax.setSax(result);
			return sax;
		}
		else
			return null;
	}
	
	private static char getLetter(List<Double> breakPoints, double element){
		char result = 'A';
		
		for(Double breakPoint: breakPoints){
			if(element < breakPoint){
				return result;
			}
			result++;
		}
		
		return result;
	}
}
